package net.ba.datasources
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.core.Application;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import net.ba.models.Cell;
	
	public class GbifDataSource extends EventDispatcher
	{
	
		private var gbifService:HTTPService;
		private var searchService:HTTPService;	
		public var results:Array = new Array(); //of CellOcc
		
		public function GbifDataSource():void {
			gbifService = new HTTPService();
			searchService = new HTTPService();
			gbifService.resultFormat = "object";
			gbifService.url = 'http://es.mirror.gbif.org/ws/rest/density/list';
			gbifService.addEventListener(ResultEvent.RESULT,onGbifServiceResponse);
			gbifService.addEventListener(FaultEvent.FAULT,onGbifServiceFault);
			searchService.resultFormat= "text";
			searchService.url = "http://es.mirror.gbif.org/species/nameSearch?maxResults=1&returnType=nameId&startIndex=0&view=json";
			
		}
		
		public function getOccurrencesByName(name:String):void {
			//Import GIBF Cells
			searchService.request.query = name;
			searchService.addEventListener(ResultEvent.RESULT, 
												function(e:ResultEvent):void {
														try{
														var rawData:String = String(e.result);
														var jsonObj:Object = JSON.decode(rawData);
														
														gbifService.request.taxonconceptkey =jsonObj.Resultset.Result[0].id;
														gbifService.showBusyCursor;
														gbifService.send();
														} catch(e:Error) {
															onSearchFault();
														}														
												});
			searchService.addEventListener(FaultEvent.FAULT,onGbifServiceFault);								
			searchService.showBusyCursor;
			searchService.send();
		}
	  
	  
	  private function onGbifServiceFault(event:FaultEvent):void {
	  	Alert.show('There has been an error');
	  }

	  private function onSearchFault():void {
	  	Alert.show('The name was not found');
	  }
	  
	  private function onGbifServiceResponse(event:ResultEvent):void {
		var arr:ArrayCollection;
		if (event.result.gbifResponse.densityRecords.densityRecord.length > 5000) {
			Alert.show('The taxon you selected has more than 5000 cells, we have trimed the result in order to avoid performance problems. Browse further the taxonomy!');
			arr = new ArrayCollection(event.result.gbifResponse.densityRecords.densityRecord.toArray().slice(0,5000));
		} else {
			arr = event.result.gbifResponse.densityRecords.densityRecord;
		}
		
		
		for each(var item:Object in arr) {
			Application.application.mapContainer.activeServerLayer.addCell(new Cell(item.cellid,item.count),false);
		}
		
		//Dispatch the event notifying we have the data back
		dispatchEvent(new Event("gbifResultsReady"));				
		
	  }	
	  		
		
	}
}